package com.matrix.app.mvc.project.member.service.impl;

import com.matrix.app.common.enums.Role;
import com.matrix.app.common.enums.Sex;
import com.matrix.app.mvc.project.member.data.MemberDto;
import com.matrix.app.mvc.project.member.data.MemberPo;
import com.matrix.app.mvc.project.member.data.MemberVO;
import com.matrix.app.mvc.project.member.repository.MemberRepository;
import com.matrix.app.mvc.project.member.service.MemberService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 项目成员服务实现
 *
 * Copyright © 海平面工作室 版权所有
 *
 * @Author: Leo
 * @Create: 2025/06/01 18:30
 * @Since 1.0
 */
@Service
public class MemberServiceImpl implements MemberService {

    private final MemberRepository repository;

    /**
     * 构造函数注入成员仓库
     * @param repository 成员仓库
     */
    public MemberServiceImpl(MemberRepository repository) {
        this.repository = repository;
    }

    /**
     * 新增成员
     * @param member 成员信息
     * @return 新增后的成员
     */
    @Override
    public MemberPo save(MemberPo member) {
        return repository.save(member);
    }

    /**
     * 根据ID删除成员
     * @param id 成员ID
     */
    @Override
    public void deleteById(Long id) {
        repository.deleteById(id);
    }

    /**
     * 根据ID查询成员
     * @param id 成员ID
     * @return 成员信息
     */
    @Override
    public MemberPo findById(Long id) {
        Optional<MemberPo> optional = repository.findById(id);
        return optional.orElse(null);
    }

    /**
     * 分页查询项目成员
     * @return 成员VO列表
     */
    @Override
    public MemberDto findMembers(MemberDto dto) {
        String searchKey = dto != null && Strings.isNotBlank(dto.getSearchKey())  ? dto.getSearchKey() : null;
        String role = dto != null && dto.getRole() != null && !dto.getRole().isEmpty() ? dto.getRole() : null;
        String sex = dto != null && dto.getSex() != null && !dto.getSex().isEmpty() ? dto.getSex() : null;
        int pageNo = dto.getPage() > 0 ? dto.getPage() : 1;
        int size = dto.getPageSize() > 0 ? dto.getPageSize() : 10;
        PageRequest pageable = PageRequest.of(pageNo - 1, size);
        var page = repository.findByConditions(searchKey, role, sex, pageable);
        var voList = page.getContent().stream().map(member -> {
            MemberVO vo = new MemberVO();
            vo.setId(member.getId());
            vo.setName(member.getName());
            vo.setPhone(member.getPhone());
            vo.setEmail(member.getEmail());
            vo.setSex(member.getSex() != null ? Sex.valueOf(member.getSex()).getDescription() : "");
            vo.setRole(member.getRole() != null ? Role.valueOf(member.getRole()).getDescription() : "");
            return vo;
        }).toList();
        dto.setItems(voList);
        dto.setTotal(page.getTotalElements());
        return dto;
    }
} 